package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.domain.ChatHistory;
import com.itheima.mapper.ChatHistoryMapper;
import com.itheima.mapper.ConversationMapper;
import com.itheima.service.IChatHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 只对会话历史列表进行操作
 */
@Service
@RequiredArgsConstructor
public class ChatHistoryImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory> implements IChatHistoryService {

    private final ConversationMapper conversationMapper;

    @Override
    public void saveChatHistory(String type, String chatId) {
        //先从数据库中查询有没有，如有有直接返回，如果没有那么就新增
        //select * from chat_history where type=? and conversation_id=?
        Long count = this.lambdaQuery().eq(ChatHistory::getType, type).eq(ChatHistory::getConversationId, chatId).count();
        if (count != null && count > 0) {
            return;
        }
        //走到这说明是第一次，那就直接新增
        ChatHistory chat = ChatHistory.builder().conversationId(chatId).createTime(LocalDateTime.now()).userId(null).title(chatId + type).type(type).build();
        this.save(chat);
    }

    @Override
    public List<String> getChatIds(String type, Long userId) {
        //select * from chat_history where tyep=? and userId=?
        List<ChatHistory> chatHistories = this.list(new LambdaQueryWrapper<ChatHistory>().eq(ChatHistory::getType, type).eq(userId != null, ChatHistory::getUserId, null));
        return chatHistories.stream().map(m -> m.getConversationId()).toList();
    }
}